const Base = require('./base.js');

module.exports = class extends Base {
  async getAction() {
    const id = this.get('id');
    if (id) {
      const data = await this.model('modulelist').join({
        table: 'module',
        join: 'left',
        as: 'm',
        on: ['module_id', 'id'] // ON 条件
      }).find();
      return this.success(data);
    } else {
      const {page = 1, pagesize = 10} = this.get();
      const list = await this.model('modulelist').join({
        table: 'module',
        join: 'left',
        as: 'm',
        on: ['module_id', 'id'] // ON 条件
      }).order('m.name ASC,modulelist.sort ASC').page(page, pagesize).countSelect({
        field: 'modulelist.id,modulelist.title,modulelist.descript,modulelist.img,modulelist.status,modulelist.sort,modulelist.created_at,modulelist.updated_at,m.id as module_id,m.name as name'
      });
      return this.success(list);
    }
  }

  async addAction() {
    try {
      const res = await this.model('modulelist').add(this.post());
      this.success(res);
    } catch (e) {
      this.fail(e.message);
    }
  }
  async changeAction() {
    const {id, ...list} = this.post();
    try {
      const res = await this.model('modulelist').where({id}).update(list);
      this.success(res);
    } catch (e) {
      this.fail(e.message);
    }
  }

  async delAction() {
    const {id} = this.post();
    try {
      const res = await this.model('modulelist').where({id}).delete();
      this.success(res);
    } catch (e) {
      this.fail(e.message);
    }
  }
};
